package com.formula.datastructure.exercise.sort.adv;

import com.formula.datastructure.util.DataUtil;

public class BinInsertSort {
    public Integer[] sort(Integer[] array) {
        int low;
        int high;
        int mid;

        for (int i = 1; i < array.length; i++) {
            Integer insertItem = array[i];

            low = 0;
            high = i - 1;

            while (low <= high) {
                mid = (low + high) / 2;
                if (array[mid] == insertItem) {
                    high = mid;
                    break;
                }
                if (array[mid] > insertItem) {
                    high = mid - 1;
                } else {
                    low = mid + 1;
                }
            }
            for (int j = i - 1; j > high; j--) {
                array[j + 1] = array[j];
            }
            // 记住这里是high + 1
            array[high + 1] = insertItem;
        }

        return array;
    }

    public static void main(String[] args) {
        int size = 20;
        int range = 50;
        Integer[] data = DataUtil.genArray(size, range);
        DataUtil.printIndex(size);
        DataUtil.printArray(data);
        BinInsertSort insert = new BinInsertSort();
        DataUtil.printArray(insert.sort(data));
    }
}
